import {Injectable, Inject} from '@angular/core';
import {User} from './model/user-model';

import {Observable, Observer} from 'rxjs/Rx';
import {GuidUtil} from '../utils/guid.util';
import {LocalStorage} from '../utils/local-storage';

@Injectable()
export class AuthUserService {

    constructor(@Inject(LocalStorage) private localStorage) {
    }

    public save(user: User): void {
        user.id = GuidUtil.getNewGUIDString();
        this.localStorage.setItem(user.username, JSON.stringify(user));
    }

    public getUser(username: string): Observable<User> {
        const userJson = this.localStorage.getItem(username);
        let user = null;
        if (!(userJson == null || userJson === '')) {
            user = JSON.parse(userJson);
        }
        return Observable.of(user);
    }

    public setCurrentUser(user: User): void {
        this.localStorage.setItem('currentUser', JSON.stringify(user));
    }

    public isLogin(): boolean {
        const userJson = this.localStorage.getItem('currentUser');
        return !(userJson == null || userJson === '');
    }

    public getCurrentUser(): Observable<User> {
        const userJson = this.localStorage.getItem('currentUser');
        let user = null;
        if (!(userJson == null || userJson === '')) {
            user = JSON.parse(userJson);
        }
        return Observable.of(user);
    }

    public removeCurrentUser(): boolean {
        this.localStorage.removeItem('currentUser');
        return true;
    }
}
